//
//  LJComposeViewController.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/26.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit
import SVProgressHUD

class LJComposeViewController: UIViewController {
    
    /// 最大输入文字
    let maxStatusLength = 25
    
    /// 工具条底部约束
    private var toolBarBottomCon: NSLayoutConstraint?
    
    /// 图片选择器底部约束
    private var pictureBrowserBottomCon: NSLayoutConstraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareUI()
        
        // 要将控制添加到子控制器管理起来
        addChildViewController(emoctionVC)
        addChildViewController(pictureSelectVC)
        
        // 注册监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willKeyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 如果图片选择器没有弹出来才弹出键盘
        if pictureBrowserBottomCon?.constant != 0 {
            textView.becomeFirstResponder()
        }
        
    }
    
    private func prepareUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavgation()
        setupTextView()
        setupPhotoBrowser()
        setupToolBar()
        setupLengthTipLabel()
    }
    
    private func setupPhotoBrowser() {
        let photoBrowserView = pictureSelectVC.view
        view.addSubview(photoBrowserView)
        
        photoBrowserView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[pb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["pb": photoBrowserView]))
        view.addConstraint(NSLayoutConstraint(item: photoBrowserView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: view.bounds.height * 0.6))
        pictureBrowserBottomCon = NSLayoutConstraint(item: photoBrowserView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.bounds.height * 0.6)
        view.addConstraint(pictureBrowserBottomCon!)
        
        
    }
    
    private func setupLengthTipLabel() {
        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
        
        // 设置文字
        lengthTipLabel.text = String(maxStatusLength)
    }
    
    private func setupToolBar() {
        view.addSubview(toolBar)
        
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        
        toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            let imageName = dict["imageName"]!
            let action = dict["action"]!
            
            let item = UIBarButtonItem(imageName: imageName)
            let button = item.customView as! UIButton
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    private func setupNavgation() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发表", style: UIBarButtonItemStyle.Plain, target: self, action: "transmit")
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置头部title
        setupNavTitle()
    }
    
    private func setupNavTitle() {
        let prefix = "发微博"
        if let name = LJUserAccount.loadUserAccount()?.screen_name {
            let titleText = prefix + "\n" + name
            let label = UILabel()
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
            label.textColor = UIColor.blackColor()
            label.numberOfLines = 0
            
            // 设置属性文本
            let attrText = NSMutableAttributedString(string: titleText)
            let nameRange = (titleText as NSString).rangeOfString(name)
            attrText.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(11), NSForegroundColorAttributeName : UIColor.lightGrayColor()], range: nameRange)
            
            label.attributedText = attrText
            label.numberOfLines = 0
            label.sizeToFit()
            
            navigationItem.titleView = label

        }else{
            navigationItem.title = prefix
        }
    }
    
    private func setupTextView() {
        view.addSubview(textView)
        
        textView.delegate = self
        
        textView.ff_Fill(view)
    }
    
    // MARK: - 通知回调方法
    @objc private func willKeyboardChangeFrame(notification: NSNotification) {
//        print(notification)
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        self.toolBarBottomCon?.constant = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    // MARK: - 导航栏按钮点击方法
    func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func transmit() {
        let length = Int(lengthTipLabel.text!)
        if length < 0 {
            SVProgressHUD.showErrorWithStatus("字数超出范围")
            return
        }
        let statusString = textView.emoctionText()
        let image = pictureSelectVC.pictures.first
        SVProgressHUD.showWithStatus("正在发送微博")
        // 调用网络工具类发送
        LJNetworkTool.shareInstance.sendStatus(statusString, image: image) { (result, error) -> () in
            if error != nil || result == nil {
                print("error\(error)")
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
            // 延迟关闭
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.close()
            })
        }
    }
    
    // MARK: - toolBar工具方法监听
    func picture() {
        // 弹出照片选择器
        pictureBrowserBottomCon?.constant = 0
        // 退下键盘
        textView.resignFirstResponder()
        // 动画
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func mention() {
        
    }
    
    func trend() {
    
    }
    
    func emoticon() {
        // 退下键盘
        textView.resignFirstResponder()

        // 延迟让表情键盘弹出
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()){ () -> Void in
            // 设置键盘
            self.textView.inputView = self.textView.inputView == nil ? self.emoctionVC.view : nil
            // 弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    func add() {
        
    }
    
    // MARK: - 懒加载
    /// 工具条
    private lazy var toolBar: UIToolbar = {
        let bar = UIToolbar()
        bar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        return bar
    }()
    /// 输入文本
    private lazy var textView: LJTextView = {
        let view = LJTextView()
        view.font = UIFont.systemFontOfSize(18)
        view.placeholder = "分享新鲜事..."
        view.backgroundColor = UIColor.brownColor()
        view.alwaysBounceVertical = true
        
        // 当滚动时推出键盘
        view.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return view
    }()
    /// 输入文本字数提示
    private lazy var lengthTipLabel: UILabel  = {
        let label = UILabel()
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(13)
        return label
    }()
    /// 表情键盘控制器
    private lazy var emoctionVC: LJEmoctionViewController = LJEmoctionViewController(textView: self.textView)
    /// 图片选择器控制器
    private lazy var pictureSelectVC: LJPictureSelectViewController = LJPictureSelectViewController()
}

//MARK: - 延展
extension LJComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        // 改变字数提示label内容
        let length = maxStatusLength - textView.emoctionText().characters.count
        lengthTipLabel.text = String(length)
        lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
    }
}